//
//  ViewController.m
//  小球移动
//
//  Created by student on 16/4/5.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>

@interface ViewController ()

@property (nonatomic,strong) CMMotionManager *motionManager;
@property (weak, nonatomic) IBOutlet UILabel *accelerInfoLabel;
@property (weak, nonatomic) IBOutlet UILabel *gyroInfoLabel;
@property (weak, nonatomic) IBOutlet UIImageView *ballImageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.motionManager = [[CMMotionManager alloc] init];
    
}

#pragma mark - 加速计与回转仪
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if(self.motionManager.accelerometerAvailable)
    {
        //更新频率
        self.motionManager.accelerometerUpdateInterval = 0.1;
        //开始监听
        [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
            NSString *info = [NSString stringWithFormat:@"加速计信息：\nX:%+.2f\nY:%+.2f\nZ:%+.2f",accelerometerData.acceleration.x,accelerometerData.acceleration.y,accelerometerData.acceleration.z];
            CGPoint p = self.ballImageView.center;
            p.x+=accelerometerData.acceleration.x*10;
            p.y-=accelerometerData.acceleration.y*10;
            self.ballImageView.center = p;
            self.accelerInfoLabel.text = info;
        }];
    }
//    else
//    {
//        NSLog(@"当前设备加速计不可用");
//    }
//    if(self.motionManager.gyroAvailable)
//    {
//        self.motionManager.gyroUpdateInterval = 0.1;
//        [self.motionManager startGyroUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMGyroData * _Nullable gyroData, NSError * _Nullable error) {
//            
//            NSString *info = [NSString stringWithFormat:@"回转信息:\nX:%+.2f\nY:%+.2f\nZ:%+.2f", gyroData.rotationRate.x,gyroData.rotationRate.y,gyroData.rotationRate.z];
//            self.ballImageView.center = CGPointMake(gyroData.rotationRate.x*10, gyroData.rotationRate.y*10);
//            self.gyroInfoLabel.text = info;
//            
//        }];
//    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    // 停止
    [self.motionManager stopGyroUpdates];
    [self.motionManager stopAccelerometerUpdates];
}

@end
